package string;

public class MultiplyStrings43 {
    public String multiply(String num1, String num2) {
        if(num1.equals("0")||num2.equals("0")){
            return "0";
        }
        String result = "";
        String before="";
        for (int i = num2.length()-1; i >=0 ; i--) {
            String r = singleMul(new StringBuilder(num1),new StringBuilder(String.valueOf(num2.charAt(i))));
            r=r+before;
            result = add(new StringBuilder(result) , new StringBuilder(r));
            before = before+"0";
        }
        return result;
    }


    private String singleMul(StringBuilder s1,StringBuilder s2){
        if(s1.length()==0|| s2.length()==0){
            return "0";
        }
        s1 = s1.reverse();
        StringBuilder result = new StringBuilder();
        int adj = 0;
        for (int i = 0; i < s1.length(); i++) {
            int r = (s1.charAt(i)-'0')*(s2.charAt(0)-'0')+adj;
            adj = r/10;
            result.append(r%10);
        }
        if(adj!=0){
            result.append(adj);
        }
        return result.reverse().toString();
    }

    private String add(StringBuilder s1,StringBuilder s2){
        if(s1.length()==0){
            return s2.toString();
        }
        if(s2.length() ==0){
            return s1.toString();
        }

        s1 = s1.reverse();
        s2 = s2.reverse();
        StringBuilder result = new StringBuilder();
        int adj = 0;
        int lenth = Math.max(s1.length(),s2.length());
        for (int i = 0; i < lenth; i++) {
            int a =0;
            int b =0;
            if(s1.length()>i){
                a = s1.charAt(i)-'0';

            }
            if(s2.length()>i){
                b = s2.charAt(i)-'0';
            }
            result.append((a+b+adj)%10);
            adj = (a+b+adj)/10;

        }
        if(adj!=0){
            result.append(adj);
        }
        return result.reverse().toString();
    }

}
